/**
 *
 */
package com.creditease.mobile.news.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.*;
import android.webkit.WebView.HitTestResult;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.creditease.mobile.R;
import com.creditease.mobile.news.db.DBUtils;
import com.creditease.mobile.news.db.NewsSQLiteOpenHelper;
import com.creditease.mobile.news.services.NewsServices;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.rss.ui.ImageSwitcherActivity;
import com.creditease.mobile.util.FileUtil;
import com.creditease.mobile.util.NetUtil;
import com.creditease.mobile.util.StreamUtil;
import com.creditease.mobile.vo.NewsDetail;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页内容 title description
 *
 * @author Administrator
 * @version 1.1.0
 * @since 2012-5-12
 */
public class NewsReaderActivity extends Activity {

    private TextView titleText;
    private WebView webView;
    private ProgressBar processbar;
    private ProgressBar newsLoadingBar;
    private String[] pics;
    private String TAG = NewsReaderActivity.class.getName();
    private NewsSQLiteOpenHelper dbHelper;
    private Handler handler;
    private static final int MSG_SUCCESS = 0;//
    private static final int MSG_FAILURE = 1;//
    private String docid;
    private String cid;
    private String newsTitle;
    private static final int LOADMORE = 3;
    private NewsServices newsServices;

    private ThreadLocal<String> newsBody = new ThreadLocal<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_reader);
        newsServices = new NewsServices();
        dbHelper = new NewsSQLiteOpenHelper(getApplicationContext());
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                switch (msg.what) {
                    case MSG_SUCCESS:// 将进度条可见
                        // reflushRss();
                        Toast.makeText(getApplicationContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                        break;
                    case MSG_FAILURE:
                        Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_SHORT).show();
                        break;
                    case LOADMORE:
                        webView.loadDataWithBaseURL(null, newsBody.get(), "text/html", "UTF-8", null);
                }
            }
        };
        // 标题
        titleText = (TextView) findViewById(R.id.titleText);
        titleText.setText(R.string.app_name);
        Intent intent = getIntent();
        docid = intent.getExtras().getString("docid");
        cid = intent.getExtras().getString("cid");
        newsTitle = intent.getExtras().getString("newsTitle");

        webView = (WebView) findViewById(R.id.newswebView);
        webView.getSettings().setJavaScriptEnabled(true);
        // webView.setInitialScale(100);
        // 支持缩放
        // webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        processbar = (ProgressBar) findViewById(R.id.newsprogressbar_updown);
        newsLoadingBar = (ProgressBar) findViewById(R.id.news_loading_bar);

        // 使页面获得焦点
        webView.requestFocus();
        WebSettings ws = webView.getSettings();
        // 首先从cache加载，如果cache不存在则从网络加载
        ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        ws.setAppCacheEnabled(true);
        ws.setPluginsEnabled(true);

        ws.setAppCacheMaxSize(50 * 1024 * 1024);
        ws.setAllowFileAccess(true);
        ws.setAppCachePath(RssConst.APPROOT);
        ws.setDatabaseEnabled(true);
        ws.setDatabasePath(RssConst.APPROOT);
        // ws.setLightTouchEnabled(true);
        webView.setWebViewClient(new RssWebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // super.onProgressChanged(view, newProgress);
                processbar.setProgress(newProgress);
                if (newProgress == 100) {
                    jsObject.loaded = false;
                    processbar.setVisibility(View.GONE);
                }
            }
        });

        StringBuilder buf = new StringBuilder();

        InputStream fisFileInputStream = null;
        String contentString = "";
        try {

            fisFileInputStream = getApplication().getAssets().open("shownews.html");
            String tempString = StreamUtil.stream2String(fisFileInputStream);
            newsBody.set(tempString);
            webView.getSettings().setDefaultTextEncodingName("UTF-8");
            webView.loadDataWithBaseURL(null, tempString, "text/html", "UTF-8", null);
            jsObject = new NewsJSObject();
            webView.addJavascriptInterface(jsObject, "news");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fisFileInputStream != null) {
                try {
                    fisFileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // final String title2 = newsDetail.title;

        webView.setOnTouchListener(new OnTouchListener() {
            private boolean flag = false;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    flag = true;
                } else if (flag && event.getAction() == MotionEvent.ACTION_UP) {
                    HitTestResult result = ((WebView) v).getHitTestResult();
                    int resultType = result.getType();
                    if (resultType == HitTestResult.IMAGE_TYPE) {
                        Intent intent = new Intent();
                        intent.setClass(getApplicationContext(),
                                ImageSwitcherActivity.class);
                        intent.putExtra("list", pics);
                        intent.putExtra("rssTitle", newsTitle);
                        intent.putExtra("imgDIR", RssConst.NEWS_IMG_CACHE);
                        int index = 0;
                        int len = RssConst.FILE_PREFIX.length();
                        String extra = result.getExtra();
                        String extraStr = "";
                        if (extra.startsWith("http")) {
                            extraStr = extra;
                        } else {
                            extraStr = extra.substring(len);
                        }
                        Log.d(TAG, "extra=" + extraStr);
                        Log.d(TAG, "pics size=" + pics.length);
                        for (String picUrl : pics) {
                            // String path = picUrl.substring(len);
                            if (extraStr.equals(picUrl)) {
                                break;
                            }
                            // File file=new File(picUrl);
                            // if (file.exists()) {
                            index++;
                            // }
                            // Log.d(TAG, "path=" + picUrl);
                        }

                        if (pics.length == 0 && index == 0) {
                            Toast.makeText(getApplicationContext(), "图片列表为空",
                                    Toast.LENGTH_SHORT).show();
                        } else if (index >= pics.length) {
                            Toast.makeText(getApplicationContext(), "图片不能正常浏览",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            intent.putExtra("index", index);
                            startActivity(intent);
                        }
                    }
                    flag = false;
                } else {
                    flag = false;
                }
                return false;
            }
        });
    }

    private NewsJSObject jsObject;

    private NewsDetail getLocalData(String docid) {

        return DBUtils.getDataFromNewsTable(dbHelper, docid);
    }

    /**
     * Description:
     *
     * @param
     * @return NewsDetail
     * @throws
     * @Author liong Create Date: 2012-5-14 上午11:09:23
     */

    private NewsDetail getData(String cid, String docid) {
        NewsDetail newsDetail = getLocalData(docid);
        if (newsDetail == null) {
            // 如果网络不可用
            if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
                handler.obtainMessage(MSG_FAILURE).sendToTarget();
                return null;
            }
            Log.d(TAG, "从网络获取数据");
            newsDetail = newsServices.getRemoteNewsDetail(cid, docid, dbHelper,false);
            /* if (newsDetail != null) {
                dbHelper.insertDataToNewsTable(cid, docid, newsDetail.body,
                        newsDetail.title, newsDetail.hasNext, newsDetail.ptime,
                        newsDetail.source);
                if (!imgs.isEmpty()) {
                    for (String img : imgs) {
                        dbHelper.insertDataToImgTable(cid, docid, img, img);
                    }
                }
            }*/

        }
        Log.d(TAG, "从数据库加载图片");
        imgs = DBUtils.getDataFromImgTable(dbHelper.getReadableDatabase(), docid);
        Log.d(TAG, "从数据库加载图片：" + imgs.size());
        return newsDetail;
    }

    private List<String> imgs = new ArrayList<String>();

    /* private NewsDetail getRemoteNewsDetail(String docid) {
            // 如果网络不可用
            if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
                handler.obtainMessage(MSG_FAILURE).sendToTarget();
                return null;
            }
            NewsDetail newsDetail = null;
            String url = ("http://c.3g.163.com/nc/article/" + docid + "/" + "head" + ".html");
            InputStream is;
            try {
                is = HttpUtils.getHttpStream(url);

                String body = null;
                String source = null;
                String ptime = null;
                String title = null;
                if (is != null) {
                    String str = StreamUtil.stream2String(is);
                    Log.d(TAG, "json=" + str);
                    JSONObject json = new JSONObject(str);
                    JSONObject array = json.getJSONObject(docid);
                    Log.d(TAG, "object=" + array);
                    body = array.getString("body");
                    title = array.getString("title");
                    source = array.getString("source");
                    String hasNext = array.getString("hasNext");
                    ptime = array.getString("ptime");

                    JSONArray jarray = array.getJSONArray("img");
                    Log.d(TAG, "hasNext=" + hasNext);
                    Log.d(TAG, "img=" + jarray);

                    for (int i = 0; i < jarray.length(); i++) {

                        JSONObject obj = jarray.optJSONObject(i);
                        String src = obj.getString("src");
                        imgs.add(src);
                    }
                    newsDetail = new NewsDetail(null, docid, title, ptime, body,
                            hasNext, source);

                    return newsDetail;
                }

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return newsDetail;
        }
    */
    private class NewsJSObject {
        private NewsDetail newsDetail;
        public boolean loaded = false;

        public String getTitle() {
            return getDNewsDetail() == null ? "" : getDNewsDetail().title;
        }

        public String getSource() {
            return getDNewsDetail() == null ? "" : getDNewsDetail().source;
        }

        public String getTime() {
            return getDNewsDetail() == null ? "" : getDNewsDetail().ptime;
        }

        public String getBody() {
            NewsDetail newsDetail2 = getDNewsDetail();
            if (newsDetail2 != null) {
                StringBuilder img = new StringBuilder();

                if (imgs != null && imgs.size() > 0) {
                    List<String> list = new ArrayList<String>();
                    for (String imgurl : imgs) {
                        img.append("<img border=\"0\" src=\"");
                        String newFileName = FileUtil.getFileName(imgurl);
                        String path = RssConst.NEWS_IMG_CACHE + newFileName;
                        File file = new File(path);
                        if (file.exists()) {
                            list.add(path);
                            // ele.attr("src", RssConst.FILE_PREFIX +
                            // path);
                            img.append(RssConst.FILE_PREFIX + path);
                        } else {
                            list.add(imgurl);
                            img.append(imgurl);
                            // PicDownloadUtil.add2Queue(imgurl, path);
                        }
                        img.append("\"/>");
                    }
                    Log.d(TAG, img.toString());
                    pics = list.toArray(new String[list.size()]);
                }
                return img.toString() + newsDetail2.body;
            }
            return "";
        }

        public String hasNext() {
            if (getDNewsDetail() != null) {
                if ("true".equals(getDNewsDetail().hasNext)) {
                    return "1";
                }
                return "0";
            }
            loaded = false;
            return "2";
        }

        public synchronized NewsDetail getDNewsDetail() {
            if (!loaded && newsDetail == null) {
                newsDetail = getData(cid, docid);
                loaded = true;
            }
            return newsDetail;
        }

        public String getMore() {

            try {
                return newsServices.getRemoteNewsDetailTail(docid, dbHelper);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }

        public String getMoreBody() {
            return "hehhehhhhhhhhh";
        }

        public void triggerFullScreen() {

        }
    }

    private class RssWebViewClient extends WebViewClient {
        // 在点击请求的是链接是才会调用，重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边。
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            processbar.setVisibility(View.VISIBLE);
            newsLoadingBar.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TextView tv = (TextView) findViewById(R.id.loadingMsg);
            // tv.setVisibility(View.GONE);
            newsLoadingBar.setVisibility(View.INVISIBLE);
            super.onPageFinished(view, url);
        }

        // 在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onLoadResource(WebView view, String url) {
            // Log.d(TAG, "URL=" + url);
            super.onLoadResource(view,
                    "http://gate.baidu.com/tc?from=opentc&src=" + url);
        }

        @Override
        public void onTooManyRedirects(WebView view, Message cancelMsg,
                                       Message continueMsg) {
            super.onTooManyRedirects(view, cancelMsg, continueMsg);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onFormResubmission(WebView view, Message dontResend,
                                       Message resend) {
            super.onFormResubmission(view, dontResend, resend);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url,
                                           boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            super.onReceivedSslError(view, handler, error);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view,
                                              HttpAuthHandler handler, String host, String realm) {
            super.onReceivedHttpAuthRequest(view, handler, host, realm);
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return super.shouldOverrideKeyEvent(view, event);
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            super.onUnhandledKeyEvent(view, event);
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
        }
    }
}
